<template>
  <div style="height: 100%; height: 100%; position: relative;" ref="fullbox">
    <div style="height: 100%; height: 100%;" ref="D3_dom">
      <!-- <p style="position:absolute;top: 10px;left: 10px;font-size: 16px;color: #fff;">{{ louceng}}</p> -->
      <!-- <p style="position:absolute;top: 10px;left: 10px;font-size: 16px;color: #fff;">倍速:{{ isSpeed }}--是否播放{{isPlay}}---12层</p> -->
    </div>
    <!-- css模型对象 人员信息 -->
    <div  id="box_people"   ref="box_people">
      <div class="box_people_title">
        <p>项目信息：{{ curItemMsg.bidName }}</p>
      </div>
      <div v-show="!playerIsShow" class="box_people_content">
        <div class="box_people_content_img">
          <div class="box_people_content_img_box"> <TouimgComponent   :src="curItemMsg.fileUrl"/></div>
        </div>
        <div class="box_people_content_msg">
          <ul>
            <li><span>姓名：{{ curItemMsg.personName }}</span></li>
            <li><span>违规行为：{{ curItemMsg.alarmName }}</span></li>
            <li><span>当前位置：{{ curItemMsg.alarmAddress }}</span></li>
            <li><span>违规时间：{{ curItemMsg.alarmTime }}</span></li>
            <li><span>视频查看：</span><span>

                <button class="jfbutton" v-for="(item,index) in curItemMsg.deviceId" :key="index" @click="handelePlay(curItemMsg,index)">视频{{ index+1 }}</button>
              </span></li>
          </ul>

        </div>
      </div>
      <div class="easyplay"  v-show="playerIsShow" >
        <div class="easyplay_button"  style="display: flex;">
          <button class="jfbutton" v-for="(item,index) in curItemMsg.deviceId" :key="index" @click="handelePlay(curItemMsg,index)">视频{{ index+1 }}</button>
          <button class="jfbutton" style="margin-left: auto;" @click="playerIsShow = false">关闭</button>
        </div>
        <easyPlayer  :url="videoUrl"/>
      </div>
    </div>

    <!-- 报警信息 -->
    <div id="wangerMsg" style="display: none;"   ref="wangerMsg">
      <div><span><img  :src="require('@/assets/imgs/dp/预警icon.png')" alt=""></span><span style="margin-left:8px">预警广播</span></div>
      <p class="wangerMsg_content">{{ WangerMsgData }}</p>
    </div>
    <!-- 报警提示音 components/Object3D/canvas/警报声.mp3 -->
    <audio ref="audioPlayer" muted :controls="false">
      <source :src="require(`@/views/witness/components/Object3D/canvas/警报声.mp3`)"  type="audio/mpeg">
    </audio>
    <!-- 进度条 -->
    <ProgressComponent v-if="progress" :onClearCanvas="clearCanvas"  :longTime="longTime" :onChange3D="onChange3D" :timeStart="timeStart"  :pointsData="pointsData" style="position: absolute;bottom: 0px;"/>
    <div class="lerg" v-if="lerg">
      <ul style="display: flex;">
        <li><img  :src="ImgWanger">出现预警</li>
        <li><div class="radius"></div>评标专家</li>
        <li><div class="radius"></div>招标代理</li>
        <li><div class="radius"></div>甲方代表</li>
      </ul>
    </div>
    <div class="lerg" v-if="gzrylerg">
      <ul style="display: flex;">
        <li><img  :src="ImgWanger">出现预警</li>
      </ul>
    </div>

    <div class="tools">
      <ul>
        <li  @click="handleTools(1)"> 
          <svg class="iconfontSvg"     aria-hidden="true" >
                <use xlink:href="#icon-fangda" ></use>
          </svg>
      
        </li>
        <li @click="handleTools(2)">
          <svg class="iconfontSvg"     aria-hidden="true"  >
                <use xlink:href="#icon-suoxiao" ></use>
          </svg>
        </li>
        <li @click="handleTools(3)">
          <svg class="iconfontSvg"     aria-hidden="true" >
                  <use xlink:href="#icon-quanping" ></use>
          </svg>
        </li>
      </ul>
    </div>
  </div>

</template>

<script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js' ;
import { CSS2DRenderer } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js"
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js"
import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js"
import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js';
import { LineGeometry } from "three/examples/jsm/lines/LineGeometry.js"
import { Line2 } from "three/examples/jsm/lines/Line2.js"
import { LineMaterial } from "three/examples/jsm/lines/LineMaterial";
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min"
import { TextGeometry } from 'three/examples/jsm/geometries/TextGeometry.js';
import { Tween, Group } from '@tweenjs/tween.js'
import  * as GeometryUtils from 'three/examples/jsm/utils/GeometryUtils'
import  {createText} from 'three/examples/jsm/webxr/Text2D'
import model,{ mesh,meshWanger,meshWangerBG,meshWangerT,texture12,texture10} from "@/views/witness/components/Object3D/canvas/model_live"; //模型对象
import TouimgComponent from "@/views/witness/components/Object3D/touimgComponent.vue"
import ProgressComponent  from "./progress.vue"
import louceng_JSON from "@/views/witness/components/Object3D/canvas/room.json"
import { peopList } from "@/views/witness/components/Object3D/canvas/const"
import { dvGetAlarm,getAlarmPlaybackURLs } from "@/api/pageViewBig"
import easyPlayer from "@/views/witness/components/Object3D/easyPlayer.vue"
import dayjs from "dayjs";
import { debounce } from "lodash";

export default {
  props:{
   
    onGetPersColor:{
      type:Function,
      default:()=>[]
    },
    xmName:{
      type:String,
      default:''
    },
    lerg:Boolean,
    gzrylerg:Boolean,
    progress:Boolean,
  },
  components:{
    TouimgComponent,
    ProgressComponent,
    easyPlayer
  },
  data() {
    return {
      playerIsShow:false,
      videoUrl:'',
      louceng:'十楼',
      //播放器
      isSpeed:1,
      isPlay:false,
      longTime:0, // 轨迹总时长
      timeStart:'YYYY-MM-DD 00:00:00', // 轨迹开始时间
      // 默认头像
      touxianglist:[require('@/assets/imgs/dp/专家.png'),require('@/assets/imgs/dp/专家2.png'),require('@/assets/imgs/dp/专家3.png')],
      D3data: {},
      peopList,
      curItemMsg:{
      },
      WangerMsgData:'',
      Wangerdata:[],
      peopleList: [],
      textarea: "",
      pos:{
        x: 0,
        y: 0,
        z: 0
      },
      positions :[], // 全部数据
      pointsData:[], // 全部数据传给子组件
      points:[], // 部分数据,
      ImgWanger:require('@/views/witness/components/Object3D/canvas/告警.png'),
    };
  },
  created(){
    // this.handlecurTime()
  },
  methods: {
        // 清空画布
    clearCanvas() { //初始化操作
      const Group_wanger =  model.getObjectByName('预警组')
      const Group_people_PBZJ =  model.getObjectByName('评标专家组')
      const Group_people_ZBDL =  model.getObjectByName('招标代理组')
      const Group_people_JFDB =  model.getObjectByName('甲方代表组')
      model.remove(Group_wanger)
      .remove(Group_people_PBZJ)
      .remove(Group_people_ZBDL)
      .remove(Group_people_JFDB)
        this.initObject3D()
    },
    initObject3D() {
      const  Group = new THREE.Group();
      const Group_wanger = Group.clone()
      const Group_people_PBZJ = Group.clone()
      const Group_people_ZBDL = Group.clone()
      const Group_people_JFDB = Group.clone()
      Group_wanger.name = '预警组'
      Group_people_PBZJ.name = '评标专家组'
      Group_people_ZBDL.name = '招标代理组'
      Group_people_JFDB.name = '甲方代表组'
      model.add(Group_wanger).add(Group_people_PBZJ).add(Group_people_ZBDL).add(Group_people_JFDB)
    },
     // 多种类型人员
     setPeopleRadiusPoints(xw,data){
      const TYPE = {
        'ZJ':{
          color:'#68F60C',
          name:'评标专家组',
        },
        'ZBDL':{
          color:'#FFC30A',
          name:'招标代理组'
        },
        'JD':{
          color:'#EB31D9',
          name:'甲方代表组'
        }
      }
   
      const name = TYPE[data.personType].name
      const Color = TYPE[data.personType].color
      const [x,y,z] = data.trackList[0].pos
      const  Group = model.getObjectByName(name)
      // console.log('Group',Group);
      
      if(!Group) return 
      const personId = data.personId
      const perMesh = Group.getObjectByName(personId)
      // console.log('perMesh',perMesh);
      
      const add = () =>{
        const geometry = new THREE.CircleGeometry(4, 32); // 半径为1，分段数为32   
        const color = new THREE.Color(Color)
        const material = new THREE.MeshBasicMaterial({ color, side: THREE.DoubleSide });// 创建材质
        const circleMesh = new THREE.Mesh(geometry, material);
              circleMesh.name = personId
              circleMesh.position.set(x*10,y*10,3)
              Group.add(circleMesh)
      }
      const edit = () => {
        perMesh.position.set(x*10,y*10,3)
      }
      const remove = () =>{
        console.log('删除');
        Group.remove(Group.getObjectByName(personId))
      }

      if(xw === 'remove'){
        remove()
        return 
      }
      if(perMesh){
        edit()
      }else{
        add()
      }
    

    },
    // 出现警告
    setWangerRadiusPoints(xw,data){
      const  Group_wanger = model.getObjectByName('预警组')
      const { personName ,id ,xyz} = data
      const add  = () =>{
        const newCircle = meshWanger.clone()
        newCircle.name = id
        const WangerBG = meshWangerBG.clone()
        WangerBG.visible = false
        WangerBG.name = '弹出框'
        
        const text = createText(personName, 8)
        const button = createText('查看', 8)
        button.name = '查看'
        button.data = data
        text.position.set(-12,0,0)
        button.position.set(12,0,0)
        WangerBG.add(text).add(button)
        WangerBG.position.set(0,12,0)
        newCircle.add(WangerBG)
        const [x,y,z]  = xyz
        newCircle.position.set(x*10, y*10, z*10)
        // return
        Group_wanger.add(newCircle)
      }
      const remove = () =>{
        Group_wanger.remove(Group_wanger.getObjectByName(id))
      }
      if(xw === 'add'){
        console.log('新增');
          add()
      }
      if(xw === 'remove'){
        remove()
      }
    },
    handleTools(TYPE){
      if(TYPE===1){
        if( this.D3data.camera.position.z < 300)  return 
        this.D3data.camera.position.z -= 100
        this.D3data.camera.updateProjectionMatrix();
      }
      if(TYPE===2){
        if( this.D3data.camera.position.z > 1500)  return 
        this.D3data.camera.position.z += 100
        this.D3data.camera.updateProjectionMatrix();
      }
      if(TYPE===3){
        this.$refs['fullbox'].requestFullscreen()
      }
    },
    // 切换楼层
    handleTabsLouceng(val){
      const arr = ['1010楼十楼','十二楼12楼12层']
      const arrText = ['十楼','十二楼']
      const changdi = model.getObjectByName('场地')
      const arrContent = [texture10,texture12]
      const index =  arr.findIndex(x=>x.includes(val))
      changdi.material.map = arrContent[index]
      this.louceng = arrText[index]
      // this.setTabRoomName(arrText[index])
    },
    // 向组件添加实时数据
    addProViewData(item){
      const calc = 10
      const JG = 1
      const { type ,data} = item
      if(type ==='location'){
        const { trackList,personId} = data
        // 如果是轨迹
        const [x,y,z] = trackList[0].pos
        this.pointsData.forEach((item,index)=>{
          if(item.personId === personId){
            item.positions.push(x * calc + JG * index,y * calc + JG * index,3)
          }
        })

        this.handleLine()
      }
      if(type ==='alarm'){
        const { id,personId,alarmName,alarmTime,alarmAddress,alarmContent,deviceId,personName,personType,xyz,bidName,fileUrl} = data
        console.log('deviceId',deviceId);
        const newdeviceId =  deviceId.split(',')
        const newalarmTime = dayjs(alarmTime).format('YYYY-MM-DD HH:mm:ss')
        const [ x,y,z ] = xyz
        this.pointsData.forEach((item,index)=>{
          if(item.personId === personId){
            item.points_waring.push(new THREE.Vector3(x * calc + JG * index,y * calc + JG * index,z+3))
            item.ids_waring.push(id)
            // 弹出预警
            this.curItemMsg = {
              alarmName,
              alarmTime:newalarmTime,
              alarmAddress,
              alarmContent,
              deviceId:newdeviceId,
              personName,
              personType,
              bidName,
              fileUrl
            }
          }
        })
        this.handleLine()
        // 再次选中预警模型
        const prambox = model.children[0] // 场地模型
        const box =  prambox.getObjectByName(id)
        const {px,py} =  this.getScreenCoordinates(box)
        document.querySelector('#box_people').style.top=  0+'px'
        document.querySelector('#box_people').style.left=   100+'px'
        document.getElementById('box_people').style.display = "block"
        const WangerMsg = this.setWangerMsg(`${alarmContent}`)
        this.handlePlay()
        setTimeout(() => {
          prambox.remove(WangerMsg)
          document.getElementById('box_people').style.display = "none"

        }, 1000 * 10);

        console.log('this.curItemMsg ',this.curItemMsg );


      }
      if(type === 'alarm.broadcast'){
        const { id,personId,alarmName,alarmTime,alarmAddress,alarmContent,deviceId,personName,personType,xyz,} = data
        const prambox = model.children[0] // 场地模型
        const WangerMsg = this.setWangerMsg(`${alarmContent}`)
        this.handlePlay()
        setTimeout(() => {
          prambox.remove(WangerMsg)
        }, 1000 * 10);
      }
      // 添加人员
      if(type === 'uwb_bind'){
        this.$parent.addPeople(data);
      }

    },
    // 播放音频
    handlePlay(){
      const audioPlayer = this.$refs['audioPlayer']
      audioPlayer.play().then(()=>{
        audioPlayer.muted = false;
      }).catch(error => {
        console.error("Error playing audio:", error);
      });

    },
    // 获取标准设备坐标
    // 获取模型在屏幕上的坐标
    getScreenCoordinates(object) {
      const width = this.$refs["D3_dom"].offsetWidth;
      const height = this.$refs["D3_dom"].offsetWidth;
      const vector = new THREE.Vector3();
      // 将模型的世界坐标转换为标准化设备坐标（NDC）
      vector.setFromMatrixPosition(object.matrixWorld);
      vector.project(this.D3data.camera);
      // 将 NDC 坐标转换为屏幕坐标
      const screenX = Math.round((vector.x + 1) * width / 2);
      const screenY = Math.round((1 - vector.y) * height / 2);
      return { px: screenX, py: screenY };
    },
    // 画线 -- 播放器
    onChange3D(lineData){
      const prambox = model.children[0] // 场地模型
      const lineGeometry  = new LineGeometry();
      // 遍历渲染模型
      for(let i in lineData){
        const { color,groupName,NeedUpdate_waring,NeedUpdate,xuanranPoints_waring_time,line2Name, wangerName,circleName,ids_waring} = lineData[i]
        let { xuanranPoints ,xuanranPoints_waring } = lineData[i]
        const lineMaterial =  new LineMaterial({
          color,
          vertexColors:false,
          linewidth:2,
          resolution: new THREE.Vector2(window.innerWidth, window.innerHeight), // 分辨率  // worldUnits: true, // false 表示单位像素
        })
        const group =  prambox.getObjectByName(groupName)
        if(!group){  // 没有该组 并且轨迹数据不为空
          const Group = new THREE.Group()
          const group = Group.clone()
          const group_wanger = Group.clone()
          group_wanger.name = wangerName //预警组
          group.add(group_wanger)
          group.name = groupName
          prambox.add(group)
        }
        if(group && NeedUpdate) { //如果线需要更新
          let linePeople =  group.getObjectByName(line2Name)
          if(!linePeople){
            // 创建线


            const geometry = lineGeometry.clone()
            geometry.setPositions(xuanranPoints)
            const  material = lineMaterial.clone()
            const line2 = new Line2(geometry,material)
            const geometry_cir = new THREE.CircleGeometry( 5, 32 );
            const material_cir = new THREE.MeshBasicMaterial({color});
            const circleMesh = new THREE.Mesh( geometry_cir, material_cir );
            circleMesh.name = circleName
            circleMesh.position.set(...xuanranPoints.slice(-3))
            line2.geometry.dynamic = true;
            line2.geometry.attributes.position.needsUpdate = true;
            line2.name = line2Name
            line2.computeLineDistances()
            line2.add(circleMesh)
            group.add(line2)
            linePeople =  group.getObjectByName(line2Name)
          }

          const circleMesh = group.getObjectByName(circleName)
          circleMesh.position.set(...xuanranPoints.slice(-3))
          linePeople.geometry.dispose()
          const geometry =  lineGeometry.clone();
          geometry.setPositions(xuanranPoints)
          linePeople.geometry = geometry
        }
        if(group && NeedUpdate_waring){ //如果预警需要更新 wangerName
          const group =  prambox.getObjectByName(groupName)
          const group_wanger =  group.getObjectByName(wangerName)
          const num = group_wanger.children.length
          xuanranPoints_waring = [...xuanranPoints_waring]
          for(let s in xuanranPoints_waring) {
            if(s >= num){
              const wangerMesh = meshWanger.clone()
              wangerMesh.position.set(...xuanranPoints_waring[s])
              wangerMesh.name = '警告'
              wangerMesh.clickName = '警告'
              wangerMesh.warngerIndex =  s
              wangerMesh.id_waring = ids_waring[s]
              group_wanger.add(wangerMesh)
            }
          }
        }
      }
    },
    setWangerMsg(data) {
      this.WangerMsgData = data           // 将css元素添加到模型中
      const DivWangerMsg =  this.$refs["wangerMsg"]
      const DivModelDivWangerMsg= new CSS2DObject(DivWangerMsg);
      DivModelDivWangerMsg.name = '警告信息'
      DivModelDivWangerMsg.position.set(800,340,0)
      const changdi = model.getObjectByName('场地')
      changdi.add(DivModelDivWangerMsg)
      return DivModelDivWangerMsg


    },
    // 创建css2渲染器
    setCss2() {
    },
    // 时间自动播放
    handlecurTime() {

      function formatDuration(totalSeconds) {
        const hours = Math.floor(totalSeconds / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const seconds = Math.floor(totalSeconds % 60);

        return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
      }

      const itmp = 1000 // 1s
      let curTime = 0
      setInterval(() => {
        curTime += 1000
        this.curTime = formatDuration(curTime / 1000)
      }, itmp)
    },
    // 计算总时长
    formatDurationlog(diffMilliseconds) {
      // // 创建两个日期对象
      //   const startDate = new Date('2023-10-01T00:00:00Z');
      //   const endDate = new Date('2023-10-02T12:30:45Z');
      //   console.log('startDate',startDate);
      //   console.log('endDate',endDate);
      //   // 计算时间差（以毫秒为单位）
      //   const diffMilliseconds = endDate - startDate;

      // 将时间差转换为秒、分钟、小时和天
      const diffSeconds = diffMilliseconds / 1000;
      const diffMinutes = diffSeconds / 60;
      const diffHours = diffMinutes / 60;
      const diffDays = diffHours / 24;
      // console.log(`总时长（毫秒）: ${diffMilliseconds}`);
      // console.log(`总时长（秒）: ${diffSeconds}`);
      // console.log(`总时长（分钟）: ${diffMinutes}`);
      // console.log(`总时长（小时）: ${diffHours}`);
      // console.log(`总时长（天）: ${diffDays}`);
      // 格式化为 HH:MM:SS
      function formatDuration(totalSeconds) {
        const hours = Math.floor(totalSeconds / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const seconds = Math.floor(totalSeconds % 60);

        return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
      }

      this.longTime = formatDuration(diffSeconds)
      // console.log(`总时长（HH:MM:SS）: ${formatDuration(diffSeconds)}`);
    },
    //  -- 生成轨迹数据
    handleLineAll(data, colors) {
    
      
      // 初始化
      if (data.length <= 0) {
        this.pointsData = data
        this.clearCanvas(data)
        return
      }
   
      const prambox = model.children[0] // 场地模型
      // 清除所有线条
      const calc = 10 // 实际米数比值
      const JG = 1 // 每人轨迹间隔
      const color = new THREE.Color()
      const persColor = []
      let statTimeStamp = new Date(data[0].trackList[0].dateTime).getTime()
      let endTimeStamp = 0
      let timeStart = data[0].trackList[0].dateTime  // YYYY - MM - DD HH:MM:SS
      for (const [index, item] of Object.entries(data)) {
        // 轨迹
        item.points = [] // 坐标[（x,y,z）]
        item.times = [] // 时间
        item.positions = [] // 轨迹点 [x,y,z,x1,y1,z1,] // 经过三维样条曲线 插值  // 只有轨迹点没有
        item.timeStamps = [] // 轨迹时间戳
        item.peopleName = item.personId
        // 预警
        item.points_waring = []
        item.times_waring = []
        item.timeStamps_waring = []
        item.ids_waring = []
        // 基础数据
        item.color = colors[index]
        item.colors = [] // 颜色
        item.setInterval = null
        item.groupName = 'group-' + item.personId
        item.line2Name = 'line2-' + item.personId
        item.wangerName = 'Plane-' + item.personId
        item.circleName = 'circle-' + item.personId
        // persColor.push({personId:item.personId,HexString: '#' + item.color.getHexString()})
        const trackList = item.trackList
        const len = trackList.length
        // 处理最长时间
        item.statTime = trackList[0].dateTime
        item.endTime = trackList.at(-1).dateTime
        const statTime = new Date(item.statTime).getTime()
        const endTime = new Date(item.endTime).getTime()


        if (statTimeStamp > statTime) {
          statTimeStamp = statTime
          timeStart = item.statTime
        }
        if (endTimeStamp < endTime) {
          endTimeStamp = endTime
        }
        // 循环创建数据
        for (let i = 0; i < len; i++) {
          if (trackList[i].type === 0) { // 路径
            const [x, y, z] = trackList[i].pos
            if(len === 1){
              item.points.push(new THREE.Vector3(x * calc + JG * index, y * calc + JG * index, z + 3));
            }
           
            item.points.push(new THREE.Vector3(x * calc + JG * index, y * calc + JG * index, z + 3));
            item.times.push(trackList[i].dateTime)
            item.timeStamps.push(trackList[i].timestamp)
          }

          if (trackList[i].type === 1) { // 告警

            const [x, y, z] = trackList[i].pos
            item.points_waring.push(new THREE.Vector3(x * calc + JG * index, y * calc + JG * index, z + 3))
            item.times_waring.push(trackList[i].dateTime)
            item.timeStamps_waring.push(trackList[i].timestamp)
            item.ids_waring.push(trackList[i].alarmId)
          }
        }
        const spline = new THREE.CatmullRomCurve3(item.points)
        const point = new THREE.Vector3();
        for (const it in item.points) { // 处理轨迹取点
          const pointx = item.points[it]
          const t = it / item.points.length;
          spline.getPoint(t, point);
          item.positions.push(pointx.x, pointx.y, pointx.z)
          // color.setHSL(t,1.0,0.5);
          // item.colors.push(color.r,color.g,color.b)
        }
      }
      this.longTime = endTimeStamp - statTimeStamp  // 轨迹总长度
      this.timeStart = timeStart // 轨迹开始时间
      this.pointsData = data
      this.clearCanvas(data)
      // 给父组件传递颜色数据
      this.onGetPersColor(persColor)
    },
    clearCanvas(data = []) { //初始化操作
      const prambox = model.children[0]


      while (prambox.children.length > 0) {
        if (prambox.children[0]){
          // if(prambox.children[0].name === '全部楼层'){
          //   break
          // }
          prambox.remove(prambox.children[0]);
        }
      }
      // this.setRoomName()
      // console.log('prambox',prambox);
      if (data.length <= 0) return
      data.forEach(item => {
        // 人分组
        const GroupPeople = new THREE.Group()
        GroupPeople.name = item.groupName
        // 创建线
        const lineGeometry = new LineGeometry();
        const lineMaterial = new LineMaterial({
          color: item.color,
          vertexColors: false,
          linewidth: 2,
          resolution: new THREE.Vector2(window.innerWidth, window.innerHeight), // 分辨率  // worldUnits: true, // false 表示单位像素
        })
        const line2 = new Line2(lineGeometry, lineMaterial)
        line2.name = item.line2Name
        const geometry_cir = new THREE.CircleGeometry(5, 32);
        const material_cir = new THREE.MeshBasicMaterial({color: item.color});
        const circleMesh = new THREE.Mesh(geometry_cir, material_cir);
        circleMesh.name = item.circleName
        // 预警分组
        const group_wanger = new THREE.Group()
        line2.add(circleMesh)
        group_wanger.name = item.wangerName  //预警组
        GroupPeople.add(group_wanger).add(line2)
        prambox.add(GroupPeople)
      });
    },
    // setTabRoomName(val){
    //   const room = model.getObjectByName('场地')
    //   room.material.map = val

    // },
    // 切换房间名称
    async setRoomName() {
      const prambox = model.children[0]
      // const room = prambox.getObjectByName('房间')
      const Group = new THREE.Group()
      const GroupRoomAll = Group.clone()
      const GroupRoomRoom10 = Group.clone()
      const GroupRoomRoom12 = Group.clone()
      GroupRoomAll.name = '全部楼层'
      GroupRoomRoom10.name = '十楼'
      GroupRoomRoom12.name = '十二楼'
      GroupRoomAll.add(GroupRoomRoom10).add(GroupRoomRoom12)
      // const groupRoom = model.getObjectByName('全部楼层') // 场地模型
      // const arr = louceng_JSON['十楼'].map(item => {
      //   item.roomName = item.name
      //   return {...item,}
      // })
      // console.log('louceng_JSON',louceng_JSON);
      // louceng_JSON['十楼'].forEach(item=>{
      //   const text = createText(item.name, 6)
      //   text.position.set(item.xl,item.yl, 0)
      //   GroupRoomRoom10.add(text)
      //   // console.log('item',item);

      // })
      // louceng_JSON['十二楼'].forEach(item=>{
      //   const text = createText(item.name, 6)
      //   text.position.set(item.xl,item.yl, 0)
      //   GroupRoomRoom12.add(text)
      //   // console.log('item',item);
      // })
      // for (const i in arr) {
      //   const text = createText(arr[i].roomName, 6)
      //   text.position.set(Number(arr[i].xl), arr[i].yl, 0)
      //   groupRoom.add(text);
      // }
      GroupRoomRoom10.visible = true;
      GroupRoomRoom12.visible = false
      prambox.add(GroupRoomAll)
    },
    // 画线直接画-- 画全部 --单人
    handleLine(indexColor) {
      let dataList = this.pointsData
      const prambox = model.children[0] // 场地模型
      const lineGeometry = new LineGeometry();
      // 遍历渲染模型
      for (let i in dataList) {
        const {color, groupName, wangerName, positions, line2Name, circleName, ids_waring} = dataList[i]
        let {points_waring} = dataList[i]
        const lineMaterial = new LineMaterial({
          color: indexColor || color,
          vertexColors: false,
          linewidth: 2,
          resolution: new THREE.Vector2(window.innerWidth, window.innerHeight), // 分辨率  // worldUnits: true, // false 表示单位像素
        })
        const material_cir = new THREE.MeshBasicMaterial({color: indexColor || color});
        // console.log('prambox',prambox);

        const group = prambox.getObjectByName(groupName)
        let linePeople = group.getObjectByName(line2Name) // 找到线

        const circleMesh = group.getObjectByName(circleName)
        circleMesh.position.set(...positions.slice(-3))
        circleMesh.material = material_cir
        linePeople.geometry.dispose()
        linePeople.material = lineMaterial.clone()
        const geometry = lineGeometry.clone();
        geometry.setPositions(positions)
        linePeople.geometry = geometry
        const group_wanger = group.getObjectByName(wangerName)
        const num = group_wanger.children.length
        points_waring = [...points_waring]
        for (let s in points_waring) {
          if (s >= num) {
            const wangerMesh = meshWanger.clone()
            wangerMesh.position.set(...points_waring[s])
            wangerMesh.name = ids_waring[s]
            wangerMesh.clickName = '警告'
            wangerMesh.warngerIndex = s
            wangerMesh.id_waring = ids_waring[s]
            group_wanger.add(wangerMesh)
          }
        }
      }

    },
    startAnimation() {
    },
    animate(time) {
      requestAnimationFrame(this.animate);
      this.group.update(time)
    },
    // 关键帧动画弃用
    keyAnm() {
      const values = points
      const posKF = new THREE.KeyframeTrack('BoxLine2.geometry.attributes.position', times, values)
      // const colorKF = new THREE.KeyframeTrack('BoxLine2.material.color', times, [1,0,0,0,0,1])
      const clip = new THREE.AnimationClip('Action', times.at(-1), [posKF])
      const mixer = new THREE.AnimationMixer(line2);
      const clipAction = mixer.clipAction(clip)
      clipAction.play()
      clipAction.loop = THREE.LoopOnce // 只播放一次
      clipAction.clampWhenFinished = true // 动画播放结束位置
      clipAction.timeScale = 0.5 //播放倍速
      // clipAction.time = 1 // 从第一秒开始播放
      // clipAction.duration = 5 //到多少s结束
      // clipAction.paused = true // 暂停
      const gui = new GUI()
      gui.add(clipAction, 'time', 0, times.at(-1)).name('播放进度条')
      const clock = new THREE.Clock()
      //   function loop (){
      //     requestAnimationFrame(loop)
      //     const frameT = clock.getDelta()
      //     mixer.update(frameT)
      // }
      // loop()
    },
    // 创建线
    handleLine2(data) {
      // 创建轨迹的几何体
      const points = [];
      for (let i = 0; i < data.length; i++) {
        let [x, y, z] = data[i].pos
        let calc = 10
        points.push(new THREE.Vector3(x * calc, y * calc, z));
      }

      const geometry = new THREE.BufferGeometry().setFromPoints(points);
      // 创建材质 红色：0xff0000
      const material = new THREE.LineBasicMaterial(
        {color: new THREE.Color('#54b7f6'), linewidth: 3});
      // 创建线条对象
      const line = new THREE.Line(geometry, material);
      // const axesHelper = new THREE.AxesHelper(100);
      // line.add(axesHelper)
      const prambox = model.children[0]
      //  const changdi =  this.D3data.scene.getObjectByName('场地');
      // line.position.
      prambox.add(line)
      //  console.log(this.D3data.scene.children[0]);
      // console.log('changdi',changdi);
      // this.D3data.scene.add(line);
    },
    //
    initDiv() {

      // 获取dom节点
      const width = this.$refs["D3_dom"].offsetWidth;
      const height = this.$refs["D3_dom"].offsetHeight;
      //场景
      const scene = new THREE.Scene();
      let selectedObjects = []
      // scene.background = new THREE.Color('#7b7e80');
      scene.background = null;
      scene.add(model);
      // model.children[0].geometry.translate(985/2,277/2,0);

      // 总辅助坐标系
      // const axesHelper = new THREE.AxesHelper(100);
      // scene.add(axesHelper);

      // 添加一个辅助网格地面 1468 × 400
      // const gridHelper = new THREE.GridHelper(1468, 400, 0x004444, 0x004444);
      // scene.add(gridHelper);

      //光源设置
      const directionalLight = new THREE.DirectionalLight(0x000000, 1);
      directionalLight.position.set(100, 60, 50);
      scene.add(directionalLight);
      const ambient = new THREE.AmbientLight(0xffffff, 2);
      scene.add(ambient);
      //渲染器和相机
      const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
      camera.position.set(0, 0, 700);
      camera.lookAt(0, 0, 0);
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(width, height);
      renderer.setClearAlpha(0);
      renderer.setPixelRatio(window.devicePixelRatio); //防止输出模糊
      renderer.outputEncoding = THREE.sRGBEncoding;
      this.$refs["D3_dom"]?.appendChild(renderer.domElement);
      // document.body.appendChild(renderer.domElement);
      // const div = document.getElementById ('tag');、
      // 将css元素添加到模型中
      //      const Div_box_people =  this.$refs["box_people"]
      // const Div_model_box_people = new CSS2DObject(Div_box_people);
      //         //改变图片网格模型顶点坐标
      // //       // Div_model_box_people.position.set(pos.getX(0),pos.getY(0),pos.getZ(0));
      // model.children[0].add(Div_model_box_people);  //插入css弹框
      // css2渲染器
      const css2Renderer = new CSS2DRenderer();
      css2Renderer.setSize(width, height);
      css2Renderer.domElement.style.position = 'absolute';
      css2Renderer.domElement.style.top = '0px';
      // css2Renderer.domElement.style.display='none';
      css2Renderer.domElement.style.pointerEvents = 'none';
      this.$refs["D3_dom"]?.appendChild(css2Renderer.domElement);
      //后处理
      // 创建渲染器通道
      const composer = new EffectComposer(renderer);
      const renderPass = new RenderPass(scene, camera);
      composer.addPass(renderPass);
      const outputPass = new OutputPass();
      composer.addPass(outputPass);
      // 创建outlinePass通道
      const v2 = new THREE.Vector2(width, height);
      const outlinePass = new OutlinePass(v2, scene, camera);
      outlinePass.visibleEdgeColor.set(0x00ffff);
      outlinePass.edgeThickness = 4;
      // console.log();
      // const xx = model.children[0].children[0]
      // outlinePass.selectedObjects = [ xx];
      // outlinePass.selectedObjects = model.children[0].children;
      outlinePass.edgeStrength = 6;
      composer.addPass(outlinePass);

      function addSelectedObject(object) {
        selectedObjects = [];
        selectedObjects.push(object);
      }

      // 坐标拾取
      renderer.domElement.addEventListener('click', (event) => {


        const px = event.offsetX;
        const py = event.offsetY;

        // 屏幕坐标px,py 转WebGL标准设备坐标x,y
        // width ,height 画布宽高度
        const x = (px / width) * 2 - 1;
        const y = -(py / height) * 2 + 1;
        const raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(new THREE.Vector2(x, y), camera)
        // console.log('model',model);

        const intersects = raycaster.intersectObjects(model.children[0].children)


        if (intersects.length > 0) {

          if (intersects[0].object.clickName !== '警告') return


          const selectedObject = intersects[0].object;
          addSelectedObject(selectedObject)
          outlinePass.selectedObjects = selectedObjects;
          // console.log('event',event.offsetX,event.offsetY)
          document.querySelector('#box_people').style.top = event.offsetY + 'px'
          document.querySelector('#box_people').style.left = event.offsetX + 'px'
          // outlinePass.selectedObjects = [intersects[0].object];
          // 选中模型的第一个模型，设置为红色
          // console.log('selectedObject.message',selectedObject.mssage);
          const id_waring = selectedObject.id_waring
          // console.log('id_waring',id_waring);
          // 掉接口
          dvGetAlarm(id_waring).then(res => {
            // console.log('res',res);

            this.curItemMsg = res.data
            let deviceId = []
            if(res.data.deviceId === ''){
              deviceId = []
            }else{
              deviceId = res.data.deviceId.split(',')
            }
            this.curItemMsg.deviceId = deviceId


            document.getElementById('box_people').style.display = "block"
          })


          // this.refs['box_people'].style.display = "block"
          intersects[0].object.material.color.set(0xff0000);
        } else {
          // this.refs['box_people'].style.display = "none"
          document.getElementById('box_people').style.display = "none"
        }

      })
      const controls = new OrbitControls(camera, renderer.domElement);
      // 缩放范围
      controls.target.set(0, 0, 0); //与lookAt参数保持一致
      controls.update(); //update()函数内会执行camera.lookAt(controls.target)
      controls.enableRotate = false; // 禁止旋转
      // controls.enableZoom = false; //禁止缩放
      // //相机位置与观察目标点最小值
      // controls.minDistance = 800;
      // //相机位置与观察目标点最大值
      // controls.maxDistance = 1500;
      controls.maxTargetRadius = 400
      controls.mouseButtons = {
        //左键平移
        LEFT: THREE.MOUSE.PAN,
        //滚轮滑动
        MIDDLE: THREE.MOUSE.DOLLY,
        //右键旋转
        RIGHT: THREE.MOUSE.ROTATE,
      };

      // 用不到
      // controls.minZoom = -1;
      // controls.maxZoom = 2;
      // controls.update();
      // controls.minTargetRadius  =
      // controls.touches = {
      //                         ONE: THREE.TOUCH.DOLLY_PAN ,
      //                         TWO: THREE.TOUCH.ROTATE,
      //                     }
      controls.update();


      // 画布跟随窗口变化
      return {
        scene,
        controls,
        renderer,
        camera,
        css2Renderer,
        composer,
        outlinePass
      };
    },
    // 播放设备
    handelePlay(item,index) {
        const { deviceId,id } = item
      this.playerIsShow = true
      const params = {
        "deviceId":deviceId[index],
        alarmId:id
      }

      getAlarmPlaybackURLs(params).then(res=>{
        if(res.code === 0){
          this.videoUrl = res.data.url
        }

      })
    },
    // 屏幕坐标转标准设备坐标
    changXY(camera, renderer, outlinePass) {
      const width = this.$refs["D3_dom"].offsetWidth;
      const height = this.$refs["D3_dom"].offsetHeight;
      renderer.domElement.addEventListener('click', function (event) {
        const px = event.offsetX;
        const py = event.offsetY;
        // 屏幕坐标px,py 转WebGL标准设备坐标x,y
        // width ,height 画布宽高度
        const x = (px / width) * 2 - 1;
        const y = -(py / height) * 2 + 1;
        // console.log('x',x);
        // console.log('y',y);
        const raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(new THREE.Vector2(x, y), camera)
        const intersects = raycaster.intersectObjects(model.children)
        if (intersects.length > 0) {
          // console.log(intersects[0]);
          outlinePass.selectedObjects = [model.children];
          // 选中模型的第一个模型，设置为红色
          intersects[0].object.material.color.set(0xff0000);

        }

      })


    },
    handleGoLeft(flg) {
      this.$refs["flexUl"].scrollBy({
        top: 0,
        left: !flg ? 90 : -90,
        behavior: "smooth"
      });
    },
    handleClear() {
      this.D3data.scene.traverse(function (obj) {
        if (obj.isMesh) {
          //判断是否是网格模型
          obj.material.color.set(new THREE.Color("#fff"));
        }
      });
    },
    handleSelect(name) {
      // 0x00FFFFFF
      this.D3data.scene.getObjectByName(name).material.color.set(new THREE.Color("#CD5C5C"));
    },
    debounce(fn, delay) {
      const delays = delay || 500;
      let timer;
      return  () =>{
        const th = this;
        const args = arguments;
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout( ()=> {
          timer = null;
          console.log(111);
          
          fn.apply(th, args);
        }, delays);
      };
    }
  },

  mounted() {

    this.D3data = this.initDiv();
   let timer
    window.onresize = () => {
      if (timer) {
          clearTimeout(timer);
        }
      timer = setTimeout( ()=> {
        timer = null;
        const width = this.$refs["D3_dom"].offsetWidth;
        const height = this.$refs["D3_dom"].offsetHeight;
        this.D3data.renderer.setSize(width, height);
        this.D3data.css2Renderer.setSize(width, height);
        this.D3data.camera.aspect = width / height;
        this.D3data.camera.updateProjectionMatrix();
        }, 300);
      
       };
    // 渲染循环
    const render = () => {
      // this.group.update(time)
      // this.D3data.renderer.render(this.D3data.scene, this.D3data.camera);
      this.D3data.composer.render()
      this.D3data.css2Renderer.render(this.D3data.scene, this.D3data.camera);
      requestAnimationFrame(render);
    }
    render();
    this.initObject3D()
    // this.setWangerMsg()
    // this.getTimeOUTneEW()
  },
  destroyed() {
    window.onresize = null;
    this.clearCanvas()

  }
};
</script>

<style scoped lang="scss">
$font14: 14px;
.button_box {
  position: absolute;
  top: 10px;
  left: 10px;
}
.lerg{
  position: absolute;
  top: 20px;
  right: 20px;
  >ul{
    display: flex;
    li{
      line-height: 30px;
      margin-right: 10px;
      display: flex;
      align-items: center;
      img{
        width: 18px;
        height:18px;
        margin-top: -4px;
        margin-right: 8px;
      }
 
      .radius{
        width: 14px;
        height: 14px;
        border-radius: 50%;
        margin-right: 8px;
       }
        &:nth-child(2) .radius{
          background: #68F60C;
        }
        &:nth-child(3) .radius{
          background: #FFC30A;
        }
        &:nth-child(4) .radius{
          background: #EB31D9;
        }
      }
    }
  }
  .tools{
    position: absolute;
    bottom: 100px;
    right: 20px;
    li{
      width: 40px;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid #576479;
      background-color: #20314e;
      &:hover{
        background-color: #2f5c9b;
      }

    }
    .iconfontSvg{
      width: 18px;
      height: 18px;
      fill: #fff;
    }
  }

#box_people {
  cursor: default;
  display: none;
  position: absolute;
  width: 360px;
  height: 300px;
  padding: 4px 6px;
  color: #fff;
  // background-image: url(~assets/imgs/dp/弹窗背景2.png);
  background-size: 100% 100%;
  // background-attachment:fixed;
  .box_people_title {
    height: 54px;
    line-height: 30px;
  }
  .easyplay{
    width: 358px;
    height: 200px;
  }
  .easyplay_button{
    display: flex;
    align-items: center;
    height: 46px;
  }
  .jfbutton {
  margin-top: 10px;
  background-color: #4395ff;
  color: #fff;
  border: 2px solid #4395ff;
  border-radius: 2px;
  margin-left: 4px;
}


  .box_people_content {
    height: 240px;
    display: flex;
    align-items: center;
    .box_people_content_img {
      min-width: 120px;
      // background-image: url('../assets/imgs/dp/头像未选中背景@2x.png');
      background-repeat: no-repeat;
      background-size: 100% auto;
      .box_people_content_img_box {
        width: 80px;
        margin-top: 18px;
        height: 120px;
        margin-left: 18px;
      }

    }

    .box_people_content_msg {
      width: 100%;
      height: 200px;
      li {
        height: 30px;

      }
    }
  }


}

#wangerMsg {
  width: 200px;
  padding: 10px 14px;
  height: 122px;
  // background: url(~assets/imgs/dp/预警背景.png);
  background-size: 100% 100%;

  img {
    width: 20px;
    height: 18px;
  }

  p {
    line-height: 30px;
  }

  .wangerMsg_content {
    margin-top: 6px;
  }

  color: #fff;

}


</style>

